#include "ZipTree.h"

ZipTree::ZipTree()
{
    this->logger_ = new ConsoleLogger();
    g_logger->addLogger(logger_);
    this->root_ = 0;
}

ZipTree::ZipTree(const char* root)
{
    this->logger_ = new ConsoleLogger();
    g_logger->addLogger(logger_);
    add(root, true);
}

ZipTree::ZipTree(const ZipTree& other)
{
    this->root_ = other.root_;
}

ZipTree::~ZipTree()
{
    delete this->logger_;
    delete this->root_;
}

void ZipTree::add(const char* element, bool condition)
{
    if (!this->root_)
    {
	this->root_ = createNode(element, condition);
    }
    else
    {
	if (strcmp(this->root_->getRoot(), element) != 0)
	    this->root_->addNode(createNode(element, condition));
    }
}

void ZipTree::add(ZipNode* node)
{
    if (!this->root_)
	this->root_ = node;
    else
	if (strcmp(this->root_->getRoot(), node->getRoot()) != 0)
	this->root_->addNode(node);
}

void ZipTree::addToNode(const char* newNodePath, bool isDirectory, const char* nodeToAddElement)
{
    ZipNode* node = this->root_->browse(nodeToAddElement);
    if (node)
    {
	node->addNode(createNode(newNodePath, isDirectory));
	INFO("Node [%s] was added to [%s]\n", newNodePath, nodeToAddElement);
    }
    else
	INFO("Node [%s] was not found", nodeToAddElement);
}

void ZipTree::remove(const char* element)
{
    if (strcmp(this->root_->getRoot(), element) == 0 && this->root_)
	clear();
    else
	this->root_->remove(element);
}

void ZipTree::setRoot(ZipNode* node)
{
    this->root_ = node;
}

void ZipTree::clear()
{
    if (this->root_)
	delete this->root_;
    this->root_ = 0;
}

bool ZipTree::isEmpty() const
{
    return this->root_ == 0;
}

void ZipTree::traverse(PF_Traverse traverseFunction)const
{
    if (this->root_)
	this->root_->traverse(traverseFunction);
}

ZipNode* ZipTree::getRoot()
{
    if (this->root_)
	return this->root_;
    return 0;
}

ZipNode* ZipTree::createNode(const char* element, bool condition)
{
    ZipNode* node = 0;
    if (condition == true)
    {
	node = new DirectoryNode(element);
    }
    else
    {
	node = new FileNode(element);
    }
    return node;
}
